<!--
 * @Author      : ZhouQiJun
 * @Date        : 2025-08-20 23:17:10
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-09-04 03:00:41
 * @Description : 要素编辑
-->
<script setup lang="ts">
import { watch } from 'vue'
import { onBeforeUnmount } from 'vue'
import { ref } from 'vue'

import { useMap } from '#ol-vue-hooks'

import { WKT } from 'ol/format'

import OlDraw from './OlDraw_'
import { geojsonObj, lineWKT, pointJson, polygonWKT } from './TheEditFeatureTest'
import { baseLayers, guiYang3857 } from './testData'

const { setTarget, gis, inited, dispose, disposed } = useMap(
  {
    center: guiYang3857 as [number, number],
    //地图初始显示级别
    zoom: 10,
    projection: 'EPSG:3857',
    bgUrl: false,
    // minZoom: 1,
    // maxZoom: 20,
  },
  baseLayers[2],
  'TheEditFeature',
)

let map = null
let olDraw: OlDraw | null = null

const selected = ref([])
watch(gis, (g) => {
  console.log({ g })
  map = g?.map
  olDraw = new OlDraw({
    //showToolBar: false,
    // geomTypes: ['Point', 'LineString', 'Polygon'],
    // freehand: false,
    // actions: ['modify', 'delete', 'translate', 'move'],
    // boundary 绘制的边界, 默认不限制, 超出边界不绘制。 wkt wkb json extent
    // 超过边界, 要处理重叠部分.
    // zIndex: 1,
    // confirmOnRemoveAll: true,
  })
  console.log({ olDraw })
  olDraw.on('changefeature', (data) => {
    console.log({ data })
  })
  olDraw.on('selectchange', (data) => {
    console.log({ data })
    selected.value = data.selected.map((item) => item.id)
  })
  olDraw.on('removefeature', (data) => {
    console.log({ data })
  })
  olDraw.on('drawcomplete', (data) => {
    console.log({ data })
  })
  olDraw.on('drawend', (event) => {
    const feature = event.feature
    // console.log({ feature })
    const wkt = new WKT().writeFeature(feature, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857',
    })
    const id = feature.getId()
    console.log({ wkt, id })
  })
  olDraw.on('modifyend', (event) => {
    const [feature] = event.features.getArray()
    // console.log({ feature })
    const wkt = new WKT().writeFeature(feature, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857',
    })
    const id = feature.getId()
    console.log({ wkt, id })
  })
  olDraw.on('translateend', (event) => {
    console.log({ event })
  })
  olDraw.on('moveend', (data) => {
    console.log({ data })
  })
  olDraw.on('freehandchange', (data) => {
    console.log({ data })
  })
  olDraw.on('completedraw', (data) => {
    console.log({ data })
  })

  g?.map?.addInteraction(olDraw)

  olDraw.addFeature(
    lineWKT,
    {
      dataProjection: 'EPSG:4326',
      //featureProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857',
    },
    '123',
  )

  olDraw.addFeature(
    polygonWKT,
    {
      dataProjection: 'EPSG:4326',
      //featureProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857',
    },
    '1234',
  )

  olDraw.addFeature(pointJson, {
    dataProjection: 'EPSG:4326',
    //featureProjection: 'EPSG:4326',
    featureProjection: 'EPSG:3857',
  })
  olDraw.addFeature(geojsonObj, {
    dataProjection: 'EPSG:4326',
    //featureProjection: 'EPSG:4326',
    featureProjection: 'EPSG:3857',
  })
  setTimeout(() => {
    olDraw?.enableFreehand()
    olDraw?.enableSelect(['1234', '123'])
  }, 3000)
  setTimeout(() => {
    olDraw?.disableSelect(['1234'])
    olDraw?.disableFreehand()
  }, 6000)
})

const showRemove = ref(false)
function onDraw(event: MouseEvent) {
  const target = event.target as HTMLButtonElement
  const classList = target.classList
  classList.add('active')
  const type = target.dataset.type as string
  if (['Point', 'LineString', 'Polygon', 'Circle'].includes(type)) {
    olDraw!.enableDraw(type)
    showRemove.value = false
  } else if (type === 'Edit') {
    olDraw!.enableModify()
    showRemove.value = true
  } else if (type === 'Translate') {
    olDraw!.enableTranslate()
  } else if (type === 'freehand') {
    //olDraw!.enableFreehand()
    olDraw!.disableFreehand()
  }
  disableOtherButtons(target)
}

function onRemove(e: MouseEvent) {
  //olDraw.removeFeature(selected.value?.[0])
  olDraw
    ?.removeAllFeatures({
      trigger: e.target as HTMLButtonElement,
      confirm: {
        confirmContent: 'confirm remove all features?',
        cancel: 'cancel',
        ok: 'ok',
      },
      //confirm: false,
    })
    .then((removed) => {
      console.log({ removed })
    })
}

function disableOtherButtons(target: HTMLButtonElement) {
  const allDrawButtons = document.querySelector('.draw-container')?.querySelectorAll('.draw-btn')
  allDrawButtons?.forEach((btn) => {
    if (!target.contains(btn)) {
      btn.classList.remove('active')
    }
  })
}
onBeforeUnmount(() => {
  map!.removeInteraction(olDraw!)
})
</script>

<template>
  <div class="TheEditFeature w-full h-full">
    <div class="map-container" :ref="setTarget">
      <div class="draw-container" @click="onDraw($event)">
        <button class="draw-btn point" title="绘制点" data-type="Point"></button>
        <button class="draw-btn line" title="绘制线" data-type="LineString"></button>
        <button class="draw-btn polygon" title="绘制面" data-type="Polygon"></button>
        <!-- TODO wkt geoJSON 不能表示圆 -->
        <!--<button class="draw-btn circle" title="绘制圆" data-type="Circle"></button>-->
        <button class="draw-btn edit" title="编辑" data-type="Edit"></button>
        <button class="draw-btn translate" title="平移" data-type="Translate">平移</button>
        <button class="draw-btn freehand" title="自由绘制" data-type="freehand">自由绘制</button>
        <button
          v-if="showRemove"
          :disable="!selected.length"
          @click="onRemove"
          class="draw-btn remove"
          title="删除"
          data-type="Edit"
        ></button>
      </div>
    </div>

    <div class="content">
      <h2>要素编辑</h2>
      <p>启用编辑：点击编辑按钮，然后单击要编辑的要素，开始编辑。按住 alt ，点击点，能移除点</p>
      <p>结束编辑：单击非要素区域，结束编辑。</p>
      <p>线面：双击结束绘制</p>
    </div>
  </div>
</template>

<style lang="scss">
.TheEditFeature {
  //position: relative;
  // scss code
  .map-container {
    position: relative;
    min-height: 500px;
    width: 100%;
  }
  .draw-container {
    position: absolute;
    top: 0.5em;
    left: 50%;
    z-index: 10;
    display: inline-flex;
    //border: 1px solid var(--ol-background-color);
    border-radius: 0 0 2px 2px;
    button:first-child {
      border-radius: 4px 0 0 4px;
    }
    button:last-child {
      border-radius: 0 4px 4px 0;
    }
    .draw-btn {
      display: block;
      box-sizing: border-box;
      height: 28px;
      width: 28px;
      padding: 0;
      border: 0;
      cursor: pointer;
      outline: none;
      overflow: hidden;
      background-color: var(--ol-accent-background-color);
      //background-color: aquamarine;
      background-repeat: no-repeat;
      background-position: center;
      &.active {
        background-color: var(--ol-brand-color);
      }
      &:not(:disabled):not(.active):hover {
        background-color: #ddd; // var(--ol-subtle-foreground-color);
      }

      &.point {
        background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m10 2c-3.3 0-6 2.7-6 6s6 9 6 9 6-5.7 6-9-2.7-6-6-6zm0 2c2.1 0 3.8 1.7 3.8 3.8 0 1.5-1.8 3.9-2.9 5.2h-1.7c-1.1-1.4-2.9-3.8-2.9-5.2-.1-2.1 1.6-3.8 3.7-3.8z"/>%3C/svg>');
      }
      &.line {
        background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m13.5 3.5c-1.4 0-2.5 1.1-2.5 2.5 0 .3 0 .6.2.9l-3.8 3.8c-.3-.1-.6-.2-.9-.2-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5c0-.3 0-.6-.2-.9l3.8-3.8c.3.1.6.2.9.2 1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5z"/>%3C/svg>');
      }
      &.polygon {
        background-image: url('/polygon.svg');
      }
      &.circle {
        background-image: url('/circle.svg');
      }
      &.edit {
        background-size: 18px 18px;
        background-image: url('/edit.svg');
      }
      &.remove {
        background-size: 18px 18px;
        background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M10,3.4 c-0.8,0-1.5,0.5-1.8,1.2H5l-1,1v1h12v-1l-1-1h-3.2C11.5,3.9,10.8,3.4,10,3.4z M5,8v7c0,1,1,2,2,2h6c1,0,2-1,2-2V8h-2v5.5h-1.5V8h-3 v5.5H7V8H5z"/>%3C/svg>');
      }
    }

    button.draw-btn + button.draw-btn {
      border-left: 1px solid #ddd;
    }
  }
  .content {
    position: absolute;
    top: 500px;
  }
}
</style>
